package dialogs;

import entities.Action;
import entities.Categorie;
import entities.Month;
import entities.Year;
import java.awt.Color;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import utils.ChocoDate;

/**
 * Dialog for adding a new action to the year.
 * @author chocoseb
 */
public class DlgAddAction extends javax.swing.JDialog {

    /**
     * Modal result of the dialog
     */
    private boolean _confirmed = false;
    /**
     * Numeric value of the amount text field. Set only if the text field contains
     * a castable value.
     */
    private double _amount;

    /** 
     * Creates new form DlgAddAction 
     */
    public DlgAddAction(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        txfDate.setValue(ChocoDate.now().getTime());
        txfDescription.setText("");
        txfAmount.setText("000.00");
        chocoCalendraOneMonth1.setMonth(ChocoDate.now().get(Calendar.MONTH), ChocoDate.now().get(Calendar.YEAR));
        cmbCategorie.removeAllItems();
        cmbCategorie.addItem("Aucun");
        for (Categorie c : Categorie.getCategorieList()) {
            cmbCategorie.addItem(c);
        }
        this.setLocationRelativeTo(parent);
    }

    /** 
     * Creates new form DlgAddAction 
     */
    public DlgAddAction(java.awt.Frame parent, boolean modal, Action p_new) {
        super(parent, modal);
        initComponents();
        txfDate.setValue(ChocoDate.now().getTime());
        txfDescription.setText("");
        txfAmount.setText("000.00");
        chocoCalendraOneMonth1.setMonth(ChocoDate.now().get(Calendar.MONTH), ChocoDate.now().get(Calendar.YEAR));
        cmbCategorie.removeAllItems();
        cmbCategorie.addItem("Aucun");
        for (Categorie c : Categorie.getCategorieList()) {
            cmbCategorie.addItem(c);
        }
        this.setLocationRelativeTo(parent);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txfDate = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        txfDescription = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txfAmount = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        spnHour = new javax.swing.JSpinner();
        chocoCalendraOneMonth1 = new utils.ChocoCalendar();
        spnMinutes = new javax.swing.JSpinner();
        jLabel4 = new javax.swing.JLabel();
        cmbCategorie = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Date :");

        txfDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));

        jLabel2.setText("Description :");

        txfDescription.setText("jTextField1");

        jLabel3.setText("Amount :");

        txfAmount.setText("jTextField2");

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnClose.setText("Close");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        spnHour.setModel(new javax.swing.SpinnerNumberModel(12, 0, 23, 1));

        chocoCalendraOneMonth1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        chocoCalendraOneMonth1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                chocoCalendraOneMonth1MouseExited(evt);
            }
        });
        chocoCalendraOneMonth1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                chocoCalendraOneMonth1FocusLost(evt);
            }
        });

        spnMinutes.setModel(new javax.swing.SpinnerNumberModel(0, 0, 59, 5));

        jLabel4.setText("Categorie :");

        cmbCategorie.setFont(new java.awt.Font("Tahoma", 1, 11));
        cmbCategorie.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbCategorie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbCategorieActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(txfDate, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(spnHour, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(spnMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(chocoCalendraOneMonth1, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnClose))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txfAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txfDescription, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
                            .addComponent(cmbCategorie, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addGap(20, 20, 20))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txfDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(spnHour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(spnMinutes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(18, 18, 18)
                .addComponent(chocoCalendraOneMonth1, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(txfDescription, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txfAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cmbCategorie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnClose)
                    .addComponent(btnAdd))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnCloseActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        try {
            getActionAmount();
            _confirmed = true;
            this.setVisible(false);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "NumberFormatException : " + e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_btnAddActionPerformed

    private void chocoCalendraOneMonth1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_chocoCalendraOneMonth1FocusLost
    }//GEN-LAST:event_chocoCalendraOneMonth1FocusLost

    private void chocoCalendraOneMonth1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_chocoCalendraOneMonth1MouseExited
//        Calendar dateSelected = chocoCalendraOneMonth1.getSelectedDate();
//        if (dateSelected != null) {
//            txfDate.setValue(dateSelected.getTime());
//        }
    }//GEN-LAST:event_chocoCalendraOneMonth1MouseExited

    private void cmbCategorieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCategorieActionPerformed
        Object selected = cmbCategorie.getSelectedItem();
        if (selected instanceof Categorie) {
            cmbCategorie.setBackground(((Categorie) selected).getColor());
        } else {
            cmbCategorie.setBackground(Color.WHITE);
        }
    }//GEN-LAST:event_cmbCategorieActionPerformed

    /**
     * Return the modal result of the dialog.
     * @return true if confirmed and false if canceled
     */
    public boolean isConfirmed() {
        return _confirmed;
    }

    /**
     * Return the date of the action from what's selected in the dialog
     * @return Calendar object 
     */
    private Calendar getActionDate() {
//        Calendar dateSelected = chocoCalendraOneMonth1.getSelectedDate();
//        if (dateSelected != null) {
//            dateSelected.set(Calendar.HOUR_OF_DAY, (Integer) spnHour.getValue());
//            dateSelected.set(Calendar.MINUTE, (Integer) spnMinutes.getValue());
//            return dateSelected;
//        }
        Date d = (Date) txfDate.getValue();
        Calendar c = new GregorianCalendar();
        c.setTime(d);
        c.set(Calendar.HOUR_OF_DAY, (Integer) spnHour.getValue());
        c.set(Calendar.MINUTE, (Integer) spnMinutes.getValue());
        return c;
    }

    /**
     * @return String contained in the description text field.
     */
    private String getActionDescription() {
        return txfDescription.getText();
    }

    /**
     * Value of the string contained in amount text field casted into double
     * @return
     * @throws NumberFormatException 
     */
    private double getActionAmount() throws NumberFormatException {
        return Double.parseDouble(txfAmount.getText());
    }

    /**
     * @return Categorie object of the new action.
     */
    private Categorie getActionCategorie() {
        Object selected = cmbCategorie.getSelectedItem();
        if (selected instanceof Categorie) {
            return (Categorie) selected;
        }
        return null;
    }

    /**
     * Add the new action to the year got in parameters.
     * @param year Year in wich to add the action.
     */
    public void addNewActionTo(Year year) {
        Calendar actionDate = getActionDate();
        if (actionDate != null) {
            Month ref = year.getMonthRef(actionDate.get(Calendar.MONTH));
            Action newAction = new Action(ref);
            newAction.setDate(actionDate);
            newAction.setDescription(getActionDescription());
            newAction.setCategorie(getActionCategorie());
            try {
                newAction.setAmount(getActionAmount());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnClose;
    private utils.ChocoCalendar chocoCalendraOneMonth1;
    private javax.swing.JComboBox cmbCategorie;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSpinner spnHour;
    private javax.swing.JSpinner spnMinutes;
    private javax.swing.JTextField txfAmount;
    private javax.swing.JFormattedTextField txfDate;
    private javax.swing.JTextField txfDescription;
    // End of variables declaration//GEN-END:variables
}
